package com.nativetoast

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.app.Dialog
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.graphics.drawable.RotateDrawable
import android.text.TextPaint
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.WindowManager
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import androidx.core.graphics.createBitmap
import androidx.core.graphics.drawable.toDrawable
import androidx.core.graphics.toColorInt
import com.coder.vincent.smart_toast.SmartToast
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReadableMap
import com.leosmart.R
import com.mrousavy.camera.core.utils.runOnUiThread
import com.nativemodules.NativeToastSpec
fun String.normalizeColor(): String {
    return when (length) {
        4 -> "#" + substring(1).map { "$it$it" }.joinToString("") // e.g. #fff -> #ffffff
        else -> this
    }
}
class NativeToast(reactApplicationContext: ReactApplicationContext):NativeToastSpec(reactApplicationContext) {
    data class Icon(
        val glyph: String,
        val size: Float,
        val fontName: String,
        val color: String
    )
    private  var dialog : Dialog? =null

    override fun showToast(options: ReadableMap?) {
        options?.let {
            val message = it.getString("message") ?: ""
            runOnUiThread {
                SmartToast.classic().show(message)
            }
        }
    }

    override fun makeToastActivity() {
        runOnUiThread {
            if(dialog==null){
                dialog=Dialog(this.currentActivity!!,R.style.BubbleDialog)
                dialog!!.setContentView(R.layout.layout_bubble_dialog)
                val rotateDrawable = dialog!!.findViewById<ImageView>(R.id.iv_loading).background as RotateDrawable
                ObjectAnimator.ofInt(rotateDrawable, "level", 0, 10000).apply {
                    duration = 1000L // 一圈耗时（单位毫秒），越小转得越快
                    repeatCount = ValueAnimator.INFINITE
                    repeatMode = ValueAnimator.RESTART
                    interpolator = LinearInterpolator() // 匀速
                    start()
                }

            }
            dialog?.show()
        }
    }


    override fun hideToastActivity() {
        runOnUiThread {
            dialog?.let {
                if (it.isShowing) {
                    it.dismiss()
                }
            }
        }
    }

    override fun showCustomToast(options: ReadableMap) {
        options.let {
            val icon = Companion.createIconDrawable(this.reactApplicationContext, icon = Companion.iconFromReadableMap(options.getMap("icon")))
            val message = it.getString("message") ?: ""
           runOnUiThread {
               SmartToast.emotion().config().iconDrawable(icon).iconSize(24f).commit().error(message)
           }
        }
    }
    override fun getName()= NAME
    companion object{
        const val NAME="NativeToast"
        fun iconFromReadableMap(options: ReadableMap?): Icon {
            val glyph = options?.getString("glyph") ?: ""
            val size = options?.getDouble("size")?.toFloat()
            val fontName = options?.getString("fontName") ?: "default"
            val color = options?.getString("color") ?: "#000000"

            return Icon(
                glyph = glyph,
                size = size?:24f,
                fontName = fontName,
                color = color
            )
        }

        fun createIconDrawable(context: Context, icon: Icon): Drawable {
           val scale = context.resources.displayMetrics.density
            val textSizePx = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP,
                icon.size,
                context.resources.displayMetrics
            )


            val paint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG).apply {
               isDither = true
               isFilterBitmap = true
               textSize=textSizePx
               color = icon.color.normalizeColor().toColorInt()
               typeface = Typeface.createFromAsset(context.assets, "fonts/${icon.fontName}.ttf")
           }

           val text = icon.glyph

           // 测量文本宽高
           val width = (paint.measureText(text) + 0.5f).toInt()
           val fontMetrics = paint.fontMetrics
           val height = (fontMetrics.bottom - fontMetrics.top + 0.5f).toInt()

           val bitmap = createBitmap(width, height)
           val canvas = Canvas(bitmap)
           canvas.setDensity(DisplayMetrics.DENSITY_XXXHIGH)  // 提升像素密度

           // 清空背景
           canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)

           // 精准 baseline 对齐
           val x = 0f
           val y = -fontMetrics.top

           canvas.drawText(text, x, y, paint)

           return bitmap.toDrawable(context.resources)
       }
    }
}